import axios from 'axios'
// import { Spin } from 'element-plus'
import { ElMessage } from 'element-plus'
import { getToken } from '../utils/auth.js'
const addErrorLog = errorInfo => {
  const { statusText, status, request: { responseURL } } = errorInfo
  let info = {
    type: 'ajax',
    code: status,
    mes: statusText,
    url: responseURL
  }
  if (!responseURL.includes('save_error_logger')){
	  
  } 
	  // store.dispatch('addErrorLog', info)
}

class HttpRequest {
  constructor (baseUrl) {
    this.baseUrl = baseUrl
    this.queue = {}
  }
  getInsideConfig () {
    const config = {
      baseURL: this.baseUrl,
      headers: {
        //
      }
    }
    return config
  }
  destroy (url) {
    delete this.queue[url]
    if (!Object.keys(this.queue).length) {
      // Spin.hide()
    }
  }
  interceptors (instance, url) {
    // 请求拦截
    instance.interceptors.request.use(config => {
      //const token = localStorage.getItem('token') // 获取token
	  const token = getToken()
      if(token !== null){
          config.headers.Authorization = token // 将token信息带上去
      }
      // 添加全局的loading...
      if (!Object.keys(this.queue).length) {
      // Spin.show() // 不建议开启，因为界面不友好
      }
      this.queue[url] = true
      return config
    }, error => {
      return false
    })

    // 响应拦截
    instance.interceptors.response.use(respon => {
		  this.destroy(url)
		  const res = respon.data
		  if (res.code !== 0) { // 根据服务器code码 自行修改判断
			// Message.Error(res.msg)
			ElMessage({
			  showClose: true,
			  message: res.msg,
			  type: 'error',
			})
			return false 
			//return Promise.reject(new Error(res.msg|| 'Error')) // 不要强制生成一个错误，劲量减少报错
		  } else {
			return res.data // 直接将data数据结果返回即可
		  }
      }, error => {
        this.destroy(url)
        let errorInfo = error.response
        if (errorInfo) {
          const { request: { statusText, status }, config } = errorInfo
          errorInfo = {
            statusText,
            status,
            request: { responseURL: config.url }
          }
          ElMessage({
            showClose: true,
            message: statusText,
            type: 'error',
          })
		  addErrorLog(errorInfo)
        }else{
			ElMessage({
            showClose: true,
            message: error.message,
            type: 'error',
          })
		}
        return false
    })
  }
  request (options) {
    const instance = axios.create({timeout:5000})
    options = Object.assign(this.getInsideConfig(), options)
    this.interceptors(instance, options.url)
    return instance(options)
  }
}
export default HttpRequest
